package com.amap.flutter.map.overlays;

import com.amap.api.maps.model.Tile;
import com.amap.api.maps.model.TileProvider;
import com.amap.api.maps.model.UrlTileProvider;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class CustomTileProvider implements TileProvider {

    private final int width = 256;
    private final int height = 256;
    private final String mUrl;

    public CustomTileProvider(String url) {
        this.mUrl = url;
    }

    public URL getTileUrl(int x, int y, int z) {
        String url = mUrl.replace("{x}", String.valueOf(x)).replace("{y}", String.valueOf(y)).replace("{z}", String.valueOf(z));
        try {
            return new URL(url);
        } catch (MalformedURLException e) {
//            throw new RuntimeException(e);
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Tile getTile(int x, int y, int z) {
        URL url;
        if ((url = this.getTileUrl(x, y, z)) == null) {
            return NO_TILE;
        } else {
            Tile tile;
            try {
                tile = Tile.obtain(this.width, this.height, a(url.openStream()));
            } catch (IOException e) {
                tile = NO_TILE;
//                var4.printStackTrace();
            }

            return tile;
        }
    }

    private static byte[] a(InputStream var0) throws IOException {
        ByteArrayOutputStream var1 = new ByteArrayOutputStream();
        a(var0, var1);
        return var1.toByteArray();
    }

    private static long a(InputStream var0, OutputStream var1) throws IOException {
        byte[] var2 = new byte[4096];

        int var3;
        long var4;
        for (var4 = 0L; (var3 = var0.read(var2)) != -1; var4 += (long) var3) {
            var1.write(var2, 0, var3);
        }

        return var4;
    }

    @Override
    public int getTileWidth() {
        return width;
    }

    @Override
    public int getTileHeight() {
        return height;
    }
}
